// e:\ApacheHtml\aa\student_data_system\client\js\api.js

// 基础配置
const API_BASE_URL = 'http://localhost:8000/api';

// 统一的请求封装函数
async function request(url, options = {}) {
    const defaultOptions = {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            // 可以在这里添加 token 等全局 header
            // 'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        ...options
    };

    try {
        const response = await fetch(`${API_BASE_URL}${url}`, defaultOptions);

        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
        }

        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Request failed:', error);
        throw error;
    }
}

// 封装常用方法
async function get(url, options = {}) {
    return request(url, { ...options, method: 'GET' });
}

async function post(url, body, options = {}) {
    return request(url, { ...options, method: 'POST', body: JSON.stringify(body) });
}

async function put(url, body, options = {}) {
    return request(url, { ...options, method: 'PUT', body: JSON.stringify(body) });
}

async function del(url, options = {}) {
    return request(url, { ...options, method: 'DELETE' });
}

// 导出供其他模块使用
export { request, get, post, put, del };